"""
CSV数据生成脚本
将模拟的传感器数据导出为CSV格式，便于分析和可视化
"""

import pandas as pd
import numpy as np
import time
from datetime import datetime, timedelta
import random
import os

def generate_simulation_data_with_timestamp():
    """
    生成带时间戳的模拟传感器数据
    返回包含25个测点的数据字典
    """
    # 基础负荷值（MW）
    base_load = 400 + random.uniform(-20, 20)
    
    # 环境温度（摄氏度）
    ambient_temp = 25 + random.uniform(-5, 5)
    
    # 风机转速（rpm）
    fan_speed = 800 + random.uniform(-100, 100)
    
    # 背压（kPa）
    backpressure = 5.5 + random.uniform(-0.5, 0.5)
    
    # 生成数据字典
    data = {
        'timestamp': datetime.now(),
        '机组负荷_MW': base_load,
        '主汽流量_t_h': 540 + random.uniform(-10, 10),
        '主汽压力_MPa': 16.5 + random.uniform(-0.5, 0.5),
        '主汽温度_℃': 540 + random.uniform(-5, 5),
        '再热蒸汽压力_MPa': 3.2 + random.uniform(-0.1, 0.1),
        '凝结水泵出口母管温度_℃': 35 + random.uniform(-2, 2),
        '凝结水流量_t_h': 1200 + random.uniform(-50, 50),
        '主给水流量_t_h': 1200 + random.uniform(-50, 50),
        '主给水温度_℃': 240 + random.uniform(-5, 5),
        '给水流量_t_h': 1200 + random.uniform(-50, 50),
        '凝结水流量_2_t_h': 35 + random.uniform(-2, 2),
        '凝结水温度_℃': 35 + random.uniform(-2, 2),
        '风机转速_rpm': fan_speed,
        '效率系数': 0.85 + random.uniform(-0.05, 0.05),
        '传热系数': 0.95 + random.uniform(-0.02, 0.02),
        '流量系数': 0.92 + random.uniform(-0.03, 0.03),
        '背压_kPa': backpressure,
        '背压_MPa': 0.0055 + random.uniform(-0.0005, 0.0005),
        '环境温度_℃': ambient_temp,
        '冷却塔效率': 0.85 + random.uniform(-0.05, 0.05),
        '凝汽器效率': 0.92 + random.uniform(-0.03, 0.03),
        '系统效率': 0.88 + random.uniform(-0.04, 0.04),
        '综合效率': 0.90 + random.uniform(-0.03, 0.03),
        '净效率': 0.87 + random.uniform(-0.04, 0.04)
    }
    
    return data

def generate_historical_data(num_records=100, time_interval_minutes=5):
    """
    生成历史数据
    参数:
        num_records: 记录数量
        time_interval_minutes: 时间间隔（分钟）
    """
    data_list = []
    base_time = datetime.now() - timedelta(minutes=num_records * time_interval_minutes)
    
    for i in range(num_records):
        # 更新时间戳
        current_time = base_time + timedelta(minutes=i * time_interval_minutes)
        
        # 生成数据
        data = generate_simulation_data_with_timestamp()
        data['timestamp'] = current_time
        
        # 添加一些趋势变化
        if i > 0:
            # 负荷随时间缓慢变化
            data['机组负荷_MW'] += random.uniform(-2, 2)
            # 环境温度日变化
            hour = current_time.hour
            temp_variation = 3 * np.sin(2 * np.pi * hour / 24)
            data['环境温度_℃'] += temp_variation + random.uniform(-1, 1)
            # 背压随负荷变化
            data['背压_kPa'] += (data['机组负荷_MW'] - 400) * 0.01 + random.uniform(-0.1, 0.1)
        
        data_list.append(data)
    
    return data_list

def generate_scenario_data(scenario='normal'):
    """
    生成不同场景的数据
    参数:
        scenario: 场景类型 ('normal', 'high_load', 'low_load', 'high_temp', 'low_temp')
    """
    data_list = []
    base_time = datetime.now() - timedelta(hours=24)
    
    if scenario == 'normal':
        # 正常工况
        base_load = 400
        ambient_temp = 25
        fan_speed = 800
        backpressure = 5.5
    elif scenario == 'high_load':
        # 高负荷工况
        base_load = 500
        ambient_temp = 30
        fan_speed = 1000
        backpressure = 7.0
    elif scenario == 'low_load':
        # 低负荷工况
        base_load = 300
        ambient_temp = 20
        fan_speed = 600
        backpressure = 4.0
    elif scenario == 'high_temp':
        # 高温工况
        base_load = 450
        ambient_temp = 35
        fan_speed = 900
        backpressure = 6.5
    elif scenario == 'low_temp':
        # 低温工况
        base_load = 380
        ambient_temp = 15
        fan_speed = 700
        backpressure = 5.0
    else:
        base_load = 400
        ambient_temp = 25
        fan_speed = 800
        backpressure = 5.5
    
    for i in range(288):  # 24小时，每5分钟一条记录
        current_time = base_time + timedelta(minutes=i * 5)
        
        # 添加日变化模式
        hour = current_time.hour
        load_variation = 20 * np.sin(2 * np.pi * (hour - 6) / 24)  # 负荷日变化
        temp_variation = 5 * np.sin(2 * np.pi * (hour - 6) / 24)   # 温度日变化
        
        data = {
            'timestamp': current_time,
            '机组负荷_MW': base_load + load_variation + random.uniform(-10, 10),
            '主汽流量_t_h': (base_load + load_variation) * 1.35 + random.uniform(-10, 10),
            '主汽压力_MPa': 16.5 + random.uniform(-0.5, 0.5),
            '主汽温度_℃': 540 + random.uniform(-5, 5),
            '再热蒸汽压力_MPa': 3.2 + random.uniform(-0.1, 0.1),
            '凝结水泵出口母管温度_℃': 35 + random.uniform(-2, 2),
            '凝结水流量_t_h': 1200 + random.uniform(-50, 50),
            '主给水流量_t_h': 1200 + random.uniform(-50, 50),
            '主给水温度_℃': 240 + random.uniform(-5, 5),
            '给水流量_t_h': 1200 + random.uniform(-50, 50),
            '凝结水流量_2_t_h': 35 + random.uniform(-2, 2),
            '凝结水温度_℃': 35 + random.uniform(-2, 2),
            '风机转速_rpm': fan_speed + random.uniform(-50, 50),
            '效率系数': 0.85 + random.uniform(-0.05, 0.05),
            '传热系数': 0.95 + random.uniform(-0.02, 0.02),
            '流量系数': 0.92 + random.uniform(-0.03, 0.03),
            '背压_kPa': backpressure + random.uniform(-0.3, 0.3),
            '背压_MPa': (backpressure + random.uniform(-0.3, 0.3)) / 1000,
            '环境温度_℃': ambient_temp + temp_variation + random.uniform(-2, 2),
            '冷却塔效率': 0.85 + random.uniform(-0.05, 0.05),
            '凝汽器效率': 0.92 + random.uniform(-0.03, 0.03),
            '系统效率': 0.88 + random.uniform(-0.04, 0.04),
            '综合效率': 0.90 + random.uniform(-0.03, 0.03),
            '净效率': 0.87 + random.uniform(-0.04, 0.04)
        }
        
        data_list.append(data)
    
    return data_list

def save_to_csv(data_list, filename, output_dir='csv_data'):
    """
    保存数据到CSV文件
    参数:
        data_list: 数据列表
        filename: 文件名
        output_dir: 输出目录
    """
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    
    # 转换为DataFrame
    df = pd.DataFrame(data_list)
    
    # 设置时间戳为索引
    df.set_index('timestamp', inplace=True)
    
    # 保存到CSV
    filepath = os.path.join(output_dir, filename)
    df.to_csv(filepath, encoding='utf-8-sig')
    
    print(f"数据已保存到: {filepath}")
    print(f"数据形状: {df.shape}")
    print(f"时间范围: {df.index.min()} 到 {df.index.max()}")
    
    return filepath

def generate_all_scenarios():
    """
    生成所有场景的CSV数据
    """
    scenarios = ['normal', 'high_load', 'low_load', 'high_temp', 'low_temp']
    
    for scenario in scenarios:
        print(f"\n生成 {scenario} 场景数据...")
        data_list = generate_scenario_data(scenario)
        filename = f"thermal_plant_data_{scenario}.csv"
        save_to_csv(data_list, filename)
    
    # 生成历史数据
    print(f"\n生成历史数据...")
    historical_data = generate_historical_data(1000, 1)  # 1000条记录，每分钟一条
    save_to_csv(historical_data, "thermal_plant_historical_data.csv")

def main():
    """
    主函数
    """
    print("=" * 60)
    print("热电厂冷端优化系统 - CSV数据生成器")
    print("=" * 60)
    
    # 生成所有场景数据
    generate_all_scenarios()
    
    print("\n" + "=" * 60)
    print("CSV数据生成完成！")
    print("生成的文件:")
    print("- thermal_plant_data_normal.csv (正常工况)")
    print("- thermal_plant_data_high_load.csv (高负荷工况)")
    print("- thermal_plant_data_low_load.csv (低负荷工况)")
    print("- thermal_plant_data_high_temp.csv (高温工况)")
    print("- thermal_plant_data_low_temp.csv (低温工况)")
    print("- thermal_plant_historical_data.csv (历史数据)")
    print("=" * 60)

if __name__ == "__main__":
    main() 